<template>
  <el-card class="box-card con-top">
    <div v-for="item in stateList" :key="item.id">
      <div class="title-box">
        <el-checkbox
          v-model="item.isCheckAll"
          :indeterminate="item.isIndeterminate"
          @change="handleCheckAllChange(item)"
        >
          {{ item.name }}
        </el-checkbox>
      </div>
      <el-checkbox-group
        v-model="item.checked"
        @change="handleCheckedCitiesChange(item)"
      >
        <el-checkbox v-for="sub in item.children" :key="sub.id" :label="sub.id">
          {{ sub.name }}
        </el-checkbox>
      </el-checkbox-group>
    </div>
    <div class="button">
      <el-button type="primary" @click="submit">确定</el-button>
      <el-button @click="clean">清空</el-button>
    </div>
  </el-card>
</template>
<script setup lang="ts">
import {
  ApiGetRoleListResource,
  ApiResourceAllList,
  ApiResourceCategoryAllList,
  ApiRoleAllResource,
} from './api'
import { useRoute } from 'vue-router'
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
const route = useRoute()

type IStateList = IResourceAllList & {
  children: IResourceAllList[]
  checked: number[]
  isCheckAll: boolean
  isIndeterminate: boolean
}

// 定义数据列表
let stateList = ref<IStateList[]>([])

if (route.query.id) {
  // 发起请求
  Promise.all([
    ApiResourceAllList(),
    ApiResourceCategoryAllList(),
    ApiGetRoleListResource(parseInt(route.query.id as string)),
  ])
    .then((res) => {
      // 处理数据结构
      stateList.value = res[1].data.map((item) => ({
        ...item,
        children: [],
        checked: [],
        // 全选
        isCheckAll: false,
        // 半选
        isIndeterminate: false,
      }))

      // 二级列表
      res[0].data.forEach((item) => {
        const temp = stateList.value.find((sub) => sub.id === item.categoryId)
        temp && temp.children.push(item)
      })

      // 查找旧数据
      res[2].data.forEach((item) => {
        const temp = stateList.value.find((sub) => sub.id === item.categoryId)
        temp?.checked.push(item.id)
      })

      // 添加全选，半选
      stateList.value.forEach((item) => {
        item.isCheckAll = item.checked.length === item.children.length

        item.isIndeterminate =
          item.checked.length > 0 && item.checked.length < item.children.length
      })
    })
    .catch((err) => {
      console.log(err)
    })
}

// 全选
const handleCheckAllChange = (val: IStateList) => {
  if (!val.isCheckAll) {
    val.checked = []
  } else {
    val.checked = val.children.map((item) => item.id)
  }

  val.isCheckAll = val.checked.length === val.children.length

  val.isIndeterminate =
    val.checked.length > 0 && val.checked.length < val.children.length
}

// 判断全选/半选
const handleCheckedCitiesChange = (val: IStateList) => {
  val.isCheckAll = val.checked.length === val.children.length

  val.isIndeterminate =
    val.checked.length > 0 && val.checked.length < val.children.length
}

const submit = () => {
  ElMessageBox.confirm('此操作将为用户添加资源, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      ApiRoleAllResource(
        parseInt(route.query.id as string),
        stateList.value.reduce<number[]>((prev, next) => {
          return prev.concat(next.checked)
        }, []),
      ).then((res) => {
        if (res.code === 200) {
          ElMessage({
            type: 'success',
            message: '添加成功！',
          })
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'success',
        message: '您已取消',
      })
    })
}

const clean = () => {
  stateList.value.forEach((item) => {
    item.isCheckAll = false
    item.isIndeterminate = false

    item.checked = []
  })
}
</script>
<style lang="less" scoped>
.title-box {
  width: 100%;
  padding: 10px;
  background-color: #f2f6fc;
}

:deep(.el-checkbox-group) {
  display: grid;
  grid-template-columns: repeat(3, 33%);
  padding: 20px;
}

.button {
  display: flex;
  justify-content: center;
  justify-items: center;
}
</style>
